// reference local blank image
Ext.namespace("scaladuct.cookieForm");
// create application
scaladuct.cookieForm.app = function() {

    //var invokeExtensionFunction = ParacolUtils.createExtensionFunction(this, extension);

    // do NOT access DOM from here; elements don't exist yet

    // private variables

    // private functions

    // public space
    return {
        // public properties, e.g. strings to translate

        componentBuilder: function(value, def) {
            return def(value);
        },

        // public methods
        init: function() {

            Ext.BLANK_IMAGE_URL = 'extjs/resources/images/default/s.gif';

            var paracol = Paracol(DefaultParacolBasicMessageFilters.addFieldsAsObject,
                    ParacolExtJSMessageFilters({
                        createComponent: this.componentBuilder
                    }),
                    DefaultParacolBasicMessageFilters.handleJsonDate);

            var mainPanel;
            var sbar;

            Ext.QuickTips.init();

            var button = Ext.get('show-btn');

            var pages = new Ext.data.Store({
                url: 'project/',
                reader: new Ext.data.JsonReader({
                    root:'entries',
                    idProperty:'id',
                    fields: [{name: 'id', mapping: 'id'},
                        {name: 'name', mapping: 'CommonMetaData.title'}]
                }),
                autoLoad: true
            });
            var pageCombo = new Ext.form.ComboBox({
                store: pages,
                displayField:'name',
                typeAhead: true,
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                emptyText:'Select a page...',
                selectOnFocus:true,
                applyTo: 'pages-combo',
                iconCls: 'no-icon'
            });

            pageCombo.on("select", function(combo, record, index) {
                var pageName = record.get('id');
                //alert("New url:" + paracol.cookieUrl);
                openWindow(pageName);
            });

            var openWindow = function(pageName) {

                if (!mainPanel) {
                    var resultLabel = new Ext.form.Label({
                    });

                    var resultPanel = new Ext.FormPanel({
                        hidden: true,
                        labelWidth: 75, // label settings here cascade unless overridden
                        url:'save-form.php',
                        frame:true,
                        defaultType: 'textfield',
                        style: 'margin-bottom: 0px',

                        items: [ resultLabel ],
                        cls: 'cookieForm',

                        onResult: function(content) {
                            resultLabel.setText(content, false);
                        }

                    });


                    var nextBtn = new Ext.Button({
                        text: 'Next',
                        handler: function(btn, ev) {
                            paracol.consumeCookie(mainPanel.getCookieFields(), mainPanel);
                        }
                    });
                    var prevBtn = new Ext.Button({
                        text: 'Previous',
                        handler: function(btn, ev) {
                            paracol.unconsumeCookie(mainPanel);
                        }
                    });
                    var cancelBtn = new Ext.Button({
                        text: 'Cancel',
                        handler: function(btn, ev) {
                            paracol.closeFlow(mainPanel);
                        }
                    });
                    var finishBtn = new Ext.Button({
                        text: 'Finish',
                        hidden: true,
                        handler: function(btn, ev) {
                            paracol.closeFlow(mainPanel);
                        }
                    });


                    var contextMenu = new Ext.menu.Menu({
                        items: [],

                        onHints: function(items, context, data) {
                            // sloučit hlavní a položkové menu
                            this.removeAll();
                            this.add(items);
                            this.showAt(data.clickPosition);
                        }
                    });
                    contextMenu.addListener("click", function(menu, item) {
                        paracol.openHint(mainPanel, item);
                    });
                    contextMenu.addListener("mouseover", function(menu, ev, item) {
                        sbar.setDescription(item);
                    });

                    var formPanel = new Ext.FormPanel({
                        hidden: true,
                        labelWidth: 75, // label settings here cascade unless overridden
                        url:'save-form.php',
                        frame:true,
                        defaultType: 'textfield',
                        style: 'margin-bottom: 0px',

                        //width: 550,
                        //height: 195,

                        items: [],
                        cls: 'cookieForm',

                        onEditCookie: function(fields) {
                            this.removeAll();
                            this.add(fields);

                            this.doLayout();
                            if (fields.length > 0) {
                                fields[0].focus();
                            }
                        }

                    });
                    formPanel.addListener("afterlayout", function(c, l) {
                        for (k = 0; k < mainPanel.getCookieFields().length; k++) {
                            var cookieField = mainPanel.getCookieFields()[k];
                            cookieField.getEl().on("contextmenu", function(ev) {
                                var selFld = Ext.ComponentMgr.get(ev.getTarget().id);
                                paracol.getHints(mainPanel, selFld.name, {
                                    selectedField : selFld.name,
                                    clickPosition : ev.getXY()
                                });
                            }, this, {stopEvent: true});

                            if (cookieField.messageValue && cookieField.messageValue.MementoInfoForField) {
                                if (cookieField.messageValue.MementoInfoForField.isParameter) {
                                    cookieField.addClass("x-memento-parameter-field-show");
                                } else {
                                    cookieField.removeClass("x-memento-parameter-field-show");
                                }
                            }

                            // validation
                            if (cookieField.messageValue && cookieField.messageValue.ValidationInfo && !cookieField.messageValue.ValidationInfo.isValid) {
                                cookieField.markInvalid(cookieField.messageValue.ValidationInfo.message);
                            } else if (cookieField.messageValue && cookieField.messageValue.CommonMetaData) {
                                // tooltips
                                var meta = cookieField.messageValue.CommonMetaData;

                                if (meta.title) {
                                    cookieField.fieldLabel = meta.title;
                                }

                                Ext.QuickTips.register({
                                    target: cookieField.id,
                                    title: meta.title,
                                    text: meta.description,
                                    width: 100,
                                    dismissDelay: 10000 // Hide after 10 seconds hover
                                });
                            }

                            cookieField.addListener("focus", function(field) {
                                sbar.setDescription(field);
                            });
                            cookieField.addListener("blur", function(field) {
                                sbar.clearStatus();
                            });

                        }
                    });

                    var menuBtn = new Ext.Button({
                        text:'Menu'
                        //                        ,
                        //                        menu: menu  // assign menu by instance
                    });
                    menuBtn.addListener("click", function(btn, ev) {
                        paracol.getHints(mainPanel, null, {
                            clickPosition : ev.getXY()
                        });
                    });
                    sbar = new Ext.ux.StatusBar({
                        //renderTo: 'basic',
                        id: 'basic-statusbar',
                        //width: 550,
                        // defaults to use when the status is cleared:
                        defaultText: 'Ready',
                        //defaultIconCls: 'default-icon',

                        // values to set initially:
                        text: 'Ready',
                        iconCls: 'x-status-valid',

                        setDescription: function(item) {
                            if (item.messageValue && item.messageValue.CommonMetaData &&
                                    item.messageValue.CommonMetaData.description) {
                                this.setStatus({
                                    text: item.messageValue.CommonMetaData.description,
                                    //iconCls: 'x-status-error',
                                    clear: true // auto-clear after a set interval
                                });
                            } else {
                                this.clearStatus();
                            }
                        },

                        // any standard Toolbar items:
                        items: [
                            prevBtn,
                            nextBtn,
                            cancelBtn,
                            finishBtn,
                            menuBtn
                        ]
                    });

                    //Ext.get(formPanel.id).setStyle("margin-bottom", "0px");

                    Ext.QuickTips.register({
                        target: 'timeFld1',
                        title: 'My Tooltip',
                        text: 'This tooltip was added in code',
                        width: 100,
                        dismissDelay: 10000 // Hide after 10 seconds hover
                    });

                    paracol.addHttpListener({
                        onRequestSent: function(message) {
                            var sb = Ext.getCmp('basic-statusbar');
                            // Set the status bar to show that something is processing:
                            sb.showBusy();
                        },

                        onResponseReceived: function(message) {
                            var sb = Ext.getCmp('basic-statusbar');
                            // once completed
                            sb.clearStatus();
                        }
                    });

                    // create the window on the first click and reuse on subsequent clicks
                    mainPanel = new Ext.Window({
                        //layout:'fit',
                        width:500,
                        closeAction:'hide',
                        plain: true,

                        title: 'ChloroForm',
                        bbar: sbar,
                        items:[
                            formPanel,
                            resultPanel
                        ],

                        getCookieFields: function() {
                            return formPanel.items.items;
                        },

                        onEditCookie: function(msg) {
                            var fields = msg.fields;
                            var context = msg.context;
                            this.setTitle("ChloroForm - " + context.name + "(" + context.page + ")");

                            formPanel.onEditCookie(fields);
                            formPanel.show();
                            resultPanel.hide();
                            if (context.canMoveBack) {
                                prevBtn.show();
                            } else {
                                prevBtn.hide();
                            }
                            nextBtn.show();
                            cancelBtn.show();
                            finishBtn.hide();
                        },

                        onHints: function(msg, data) {
                            contextMenu.onHints(msg.items, msg.context, data);
                        },

                        onResultStarterReady: function(msg) {
                            var context = msg.context;
                            this.setTitle("ChloroForm - " + context.name);

                            formPanel.hide();
                            resultPanel.show();
                            nextBtn.hide();
                            //prevBtn.hide();
                            cancelBtn.show();
                            finishBtn.show();
                        },

                        onResult: function(msg) {
                            var content = msg.content;
                            var context = msg.context;
                            this.setTitle(context.name);
                            this.onResultStarterReady({context: msg.context});
                            resultPanel.onResult(content);
                        },

                        onEnd: function(msg) {
                            mainPanel.close();
                            mainPanel = null;
                        }
                    });

                    paracol.startEdit("", pageName, mainPanel);

                    mainPanel.show(this);

                }

                button.on('click', openWindow);
            };


        }
    };
}(); // end of app
